<?php

namespace app\api\controller;

use app\admin\validate\Pay;
use app\api\model\Order;
use app\common\controller\Api;
use EasyWeChat\Kernel\Messages\Location;
use fast\Http;
use think\Db;
use think\exception\ValidateException;
use think\Request;
use think\Validate;

/**
 * 示例接口
 */
class Base extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    protected array $paramInfo = [];

    public function _initialize()
    {

        parent::_initialize();

        $params = $this->request->param();
        if (!isset($params['ip'])){
            $this->error('请传入IP');
        }

        $area = $this->getArea($params['ip']);
        $params['province'] = $area['province'];
        $params['city'] = $area['city'];


        //先创建订单，如果没有openid再微信授权
        if (empty($params['orderpostid'])) {

            //查看是否有满足条件的post请求
            $orderPost = Db('orderPost')->where(['ordersn' => $params['ordersn'], 'price' => $params['price'],'paytype' => $params['paytype'], 'payplatform' => $params['payplatform']])->find();

            if (isset($orderPost['pay_info']) && $orderPost['pay_info'] !== null) {
                $oauthUrl = $this->repeatAuthorize($orderPost);
                $authData = [
                    'isoauth' => 1,
                    'url'       =>$oauthUrl
                ];

                $this->success('', $authData);

            }else{
                $platform = $this->request->param('platform');

                $platformInfo = Db('platformLists')->where(['enname' => $platform])->find();

                //寻找可用商户号
                if ($platformInfo['codetype'] == 0) {
                    $payCodeList = Db('pay_code_lists')
                        ->where(function ($query) use ($platformInfo) {
                            $query->where('platform_lists_id', 0)
                                ->whereOr('platform_lists_id', $platformInfo['id']);
                        })
                        ->find();
                } else {
                    $payCodeList = Db('pay_code_lists')
                        ->where('platform_lists_id', $platformInfo['id'])
                        ->find();
                }

                if (!$payCodeList){
                    $this->error('无可用商户号');
                }

                $orderInstance = new Order();
                $orderPostId = $orderInstance->createOrderPost($params);
            }
        }else{
            $orderPostId = $params['orderpostid'];
        }

        //实际认证流程
        if ($orderPostId >0 ){
            $params = Db('orderPost')->where(['id' => $orderPostId])->find();

            //查询订单状态
            $order = Db('orderLists')->where(['ordersn' => $params['ordersn']])->find();
            if ($order && $order['status'] == '支付失败'){
                $this->error('该笔订单已失效，请重新下单');
            }
        }

        $openid  = $params['openid'] ?? '';

        if (empty($openid) && is_weixins()) {
            $oauthUrl = $this->authorize($params,$orderPostId);
            $authData = [
                'isoauth' => 1,
                'url'       =>$oauthUrl
            ];

            $this->success('', $authData);exit;
        }



        $validate = new Pay();
        if (!$validate->scene('add')->check($params)) {
            $this->error($validate->getError());
        }

        //获取平台KEY
        $key = Db('platformLists')->where('name','=',$params['platform'])->value('key');

        $data = array(
            'ordersn'   => $params['ordersn'],
            'price' => $params['price'],
            'paytype' => $params['paytype'],
            'callbackurl'   => $params['callbackurl'],
            'payplatform' => $params['payplatform'],
            'nonce_str' => $params['nonce_str'],
        );


        $hmacVal = urlencode($this->hmacRequest($data,$key));
//        $signs = $params['signs'];

//        if ($hmacVal != $signs){
////            $this->error('验签失败');
//        }

        $this->paramInfo = $params;
    }

    protected function hmacRequest($params, $key, $encryptType = "1")
    {
        if ("1" == $encryptType) {
            return md5(implode("", $params) . $key);
        } else {
            $private_key = openssl_pkey_get_private($key);
            $params = implode("", $params);
            openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
            openssl_free_key($private_key);
            $sign = base64_encode($sign);
            return $sign;
        }
    }

//    function getOpenId($code,$appid,$appsecret)
//    {
//
//        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
//
//        // 发送 HTTP 请求
//        $response = file_get_contents($url);
//        $data = json_decode($response, true);
//
//        // 检查返回结果
//        if (isset($data['openid'])) {
//            return $data['openid']; // 返回 openid
//        } else {
//            // 返回错误信息
//            return $data['errmsg'] ?? '获取 openid 失败';
//        }
//    }

    public function authorize($params,$orderid)
    {

        if (!isset($params['appid'])) {
            throw new \Exception('appid 不能为空');
        }

        $appid = $params['appid'];

        $query = ['orderpostid' => $orderid];
        $queryString = http_build_query($query);

        $domain = Request::instance()->domain(); // 例如：https://www.example.com

        $redirectUri = urlencode($domain . '/api/Oauth/index');

        $scope = 'snsapi_base'; // 静默授权

        $state = urlencode($queryString);

        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }

    public function repeatAuthorize($params)
    {

        $domain = Request::instance()->domain(); // 例如：https://www.example.com

        return ($domain . '/index.html#/?orderpostid='.$params['id'].'&price='.$params['price']);
    }

    public function getArea($ip){
        global $_W;

//        $ip = '182.117.161.94';
        $url = "https://api.map.baidu.com/location/ip?ip=$ip&coor=bd09ll&ak=0jpCoax04lECkLjHYFP1FqSyccm2YvZQ";

        $response = Http::get($url);
        $response = json_decode($response, true);

        $ret = ($response['content']);

        $ret = $ret['address_detail'];


        if (trim($ret['city'] =='黔东南自治州')){
            $ret['city'] = '黔东南苗族侗族自治州';
        }

        if (trim($ret['city'] =='黔西南自治州')){
            $ret['city'] = '黔西南布依族苗族自治州';
        }

        if (trim($ret['city'] =='湘西自治州')){
            $ret['city'] = '湘西土家族苗族自治州';
        }

        if (trim($ret['city'] =='北京辖区')){
            $ret['city'] = '北京市';
        }

        if (trim($ret['city'] =='天津辖区')){
            $ret['city'] = '天津市';
        }

        $ret['ip'] = $ip;

//        $ret = json_decode($ret, true);
        return $ret;
    }
}
